package com.fourforfo.fourmall.product.service.impl;

import com.fourforfo.fourmall.product.entity.AttrEntity;
import com.fourforfo.fourmall.product.service.AttrAttrgroupRelationService;
import com.fourforfo.fourmall.product.service.AttrService;
import com.fourforfo.fourmall.product.service.ProductAttrValueService;
import com.fourforfo.fourmall.product.vo.AttrGroupRespVO;
import com.fourforfo.fourmall.product.vo.ProductItemVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourforfo.common.utils.PageUtils;
import com.fourforfo.common.utils.Query;

import com.fourforfo.fourmall.product.dao.AttrGroupDao;
import com.fourforfo.fourmall.product.entity.AttrGroupEntity;
import com.fourforfo.fourmall.product.service.AttrGroupService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    AttrAttrgroupRelationService relationService ;

    @Autowired
    AttrService attrService ;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        String key = (String) params.get("key");

        //select * from pms_attr_groupp where catelog_id={catelogId} and (attr_group_id=key or attr_group_name like %key%);
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_group_id",key).or().like("attr_group_name",key);
            });
        }
        if(catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                queryWrapper);
        return new PageUtils(page);

    }

    /**
     * 获取分类下所有分组&关联属性
     * @param catelogId 接受商品分类id
     */
    @Override
    public List<AttrGroupRespVO> listGroupAttrByCatId(Long catelogId) {
        //根据分类id查出所有分组信息
        List<AttrGroupEntity> entities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
        if(entities==null||entities.size()==0) return new ArrayList<AttrGroupRespVO>();
        //查询所有属性
        List<AttrGroupRespVO> respVOS = entities.stream().map((item)->{
            AttrGroupRespVO respVO = new AttrGroupRespVO();
            BeanUtils.copyProperties(item,respVO);
            if(respVO.getAttrGroupId()!=null){
                //根据分组id查询所有属性，可以直接调用attrService.listAttrByGroup(groupId)
                List<AttrEntity> attrEntities = attrService.listAttrByGroup(respVO.getAttrGroupId());
                if(attrEntities!=null){
                    respVO.setAttrs(attrEntities);
                }

            }

            return respVO;
        }).collect(Collectors.toList());

        return respVOS;
    }

    /**
     * 当该分组在attrAttrGroupRelation中没有任何关联的属性信息时
     * 删除该分组信息
     */
    @Transactional
    @Override
    public void removeNoAnyRelation(List<Long> attrGroupIds) {

        relationService.removeByAttrGroupIds(attrGroupIds);
        this.removeByIds(attrGroupIds);
    }

    /**
     * 获取Spu规格参数组及组下的规格参数
     * 查询当前spu对应的所有属性的分组信息以及当前分组下的所有属性对应的值
     * @param spuId
     * @return
     */
    @Override
    public List<ProductItemVO.SpuItemBaseAttrVO> getAttrGroupWithAttrsBySpuId(Long spuId) {

        //查询当前spu对应的所有属性的分组信息以及当前分组下的所有属性对应的值
        /**
         * 1.根据spuId从pms_product_attr_value表中获取所有attrId属性
         *   SELECT attr_id FROM pms_product_attr_value AS e WHERE e.spu_id=13 AND e.attr_id=d.attr_id
         *
         * 2.根据第1步获取的attrIds从pms_attr_attrgroup_relation表中查出所有attr_group_id并按attr_group_id分组
         *   SELECT d.attr_group_id FROM pms_attr_attrgroup_relation AS d
         *     WHERE EXISTS(第1步的SQL) AND d.attr_group_id=c.attr_group_id GROUP BY c.attr_group_id
         *
         * 3.根据第2步获取的attr_group_id从表pms_attr_group 查出所有符合条件的attr_group_id和attr_group_name属性
         *   SELECT c.attr_group_id,c.attr_group_name from pms_attr_group AS c WHERE EXISTS(第2步的SQL)
         *
         * 4.将表pms_attr_attrgroup_relation 与第3步获取的attr_group_id和attr_group_name数据根据attr_group_id进行left join操作
         *   SELECT a.attr_id,a.attr_group_id,b.attr_group_name
         *     FROM pms_attr_attrgroup_relation AS a
         *     LEFT JOIN ( [第3步的SQL] ) AS b ON a.attr_group_id=b.attr_group_id;
         *
         * 5.将表`pms_attr_attrgroup_relation` 与第4步获取的`attr_id`，`attr_group_id`和`attr_group_name`数据根据`attr_id`进行`left join`操作
         *   SELECT x.attr_id,x.attr_name,x.attr_value,y.attr_group_id,y.attr_group_name
         * 	   FROM pms_product_attr_value AS x
         * 	   LEFT JOIN (第4步的SQL) AS y
         *     ON x.attr_id=y.attr_id;
         */

        List<ProductItemVO.SpuItemBaseAttrVO> results = attrAttrgroupRelationService.listAttrGroupAndAttr(spuId);



        return results;
    }


}